package com.fzx.fzwsupplysystem.view;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.DrawableRes;
import android.support.annotation.StyleRes;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fzx.fzwsupplysystem.R;


/**
 * 描述：普通提示的对话框，对话框周期：show()-->super.show()-->onCreate()-->dismiss()
 * <p>
 * 项目名称：CustomDialog
 * 创建人：  FangZhixin
 * 创建时间：2019/3/16
 */
public class CustomDialog extends Dialog {

    private static final String TAG = "CustomDialog";
    private Context mContext;

    private View mView;
    private LinearLayout ll_dialog_content;//标题父容器
    private RelativeLayout rl_dialog_title;//标题父容器
    private LinearLayout ll_dialog_center;//提示信息父容器
    private TextView tv_title;//标题
    private TextView tv_time;//倒计时
    private TextView tv_note;//对话框中间部分提示信息
    private Button btn_positive;//确认按钮
    private Button btn_negative;//取消按钮

    //对话框属性
    private int mWidth = 0;//设置宽
    private int mHeight = 0;//设置高
    private int mBackgroundColor;//设置背景颜色
    private int mBackgroundResId;//设置背景资源
    private int mButtonResId;//设置按钮资源
    private Drawable mBackgroundDrawable = null;//设置背景图片
    private int mGravity;//设置位置属性
    //自由设置位置，前提是需要设置Gravity.TOP|Gravity.LEFT
    private boolean isRandPosition;
    private int mPositionX;
    private int mPositionY;
    private int mWindowAnimations;

    private boolean cancelButton = false;//设置是否有取消按钮
    private boolean yesButton = false;//设置是否有确认按钮
    private View.OnClickListener positiveListener;
    private View.OnClickListener negetiveListener;
    private String mTitle;//设置标题
    private String mMessage;//设置提示信息
    private long mCountTime = -1;//设置倒计时时间，单位毫秒
    private CountTimer countTimer;

    private OnDialogListener mListener;

    public interface OnDialogListener {
        //显示对话框前调用，在show()之前
        void onPrepare();

        //显示对话框时调用，在onCreate()后
        void onShow();

        //关闭对话框调用，调用dismiss()后
        void onFinish();

        //对话框超时关闭后调用，并不会调用到onFinish()
        void onTimeout();
    }

    public void setOnDialogListener(OnDialogListener listener) {
        this.mListener = listener;
    }

    public CustomDialog(Context context) {
        super(context);
        this.mContext = context;
        initView();
    }

    public CustomDialog(Context context, int themeResId) {
        super(context, themeResId);
        this.mContext = context;
        initView();
    }

    protected CustomDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        this.mContext = context;
        initView();
    }

    public CustomDialog(Context context, int width, int height) {
        super(context);
        this.mContext = context;
        this.mWidth = width;
        this.mHeight = height;
        initView();
    }

    public CustomDialog(Context context, int width, int height, int themeResId) {
        super(context, themeResId);
        this.mContext = context;
        this.mWidth = width;
        this.mHeight = height;
        initView();
    }

    @Override
    public void show() {
        super.show();
    }

    public void showDialog() {
        if (!this.isShowing()) {
            if (mListener != null) {
                mListener.onPrepare();
            }
            show();
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
    }

    public void closeDialog() {
        if (this.isShowing()) {
            dismiss();
            if (mListener != null) {
                mListener.onFinish();
            }
            if (countTimer != null) {
                Log.i(TAG, "cancel: ");
                countTimer.cancel();
                countTimer = null;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置无标题
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(mView);
        initData();
        if (mListener != null) {
            mListener.onShow();
        }
    }

    //初始化控件
    private void initView() {
        mView = LayoutInflater.from(mContext).inflate(R.layout.view_custom_dialog_layout, null);
        ll_dialog_content = mView.findViewById(R.id.ll_dialog_content);
        rl_dialog_title = mView.findViewById(R.id.rl_dialog_title);
        ll_dialog_center = mView.findViewById(R.id.ll_dialog_center);
        tv_title = mView.findViewById(R.id.tv_title);
        tv_time = mView.findViewById(R.id.tv_time);
        tv_note = mView.findViewById(R.id.tv_note);
        btn_positive = mView.findViewById(R.id.btn_positive);
        btn_negative = mView.findViewById(R.id.btn_negative);
    }

    private void initData() {
        Window win = this.getWindow();
        if (win != null) {
            WindowManager.LayoutParams lp = win.getAttributes();
            //设置宽高
            if (mWidth != 0) {
                lp.width = mWidth;
            } else {
                lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            }
            if (mHeight != 0) {
                lp.height = mHeight;
            } else {
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            }
            //设置位置属性
            if (mGravity != 0) {
                if (mGravity == Gravity.TOP || mGravity == Gravity.BOTTOM) {
                    lp.gravity = mGravity;
                } else {
                    lp.gravity = Gravity.CENTER;
                }
            }
            //设置自由位置
            if (isRandPosition) {
                lp.gravity = Gravity.TOP | Gravity.START;
                lp.x = mPositionX;
                lp.y = mPositionY;
            }
            //设置显示和隐藏动画
            if (mWindowAnimations != 0) {
                lp.windowAnimations = mWindowAnimations;
            }
            //设置属性到窗口
            win.setAttributes(lp);
            //设置背景
            if (mBackgroundResId != 0) {
//                win.setBackgroundDrawableResource(mBackgroundResId);
                ll_dialog_content.setBackgroundResource(mBackgroundResId);
            }
            if (mBackgroundDrawable != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    ll_dialog_content.setBackground(mBackgroundDrawable);
                } else {
                    win.setBackgroundDrawable(mBackgroundDrawable);
                }
            }
            if (mBackgroundColor != 0) {
                ll_dialog_content.setBackgroundColor(mBackgroundColor);
            }
        }
        //设置标题
        if (mTitle != null && !"".equals(mTitle)) {
            rl_dialog_title.setVisibility(View.VISIBLE);
            tv_title.setText(mTitle);
        } else {
            rl_dialog_title.setVisibility(View.GONE);
        }
        //设置提示信息
        if (mMessage != null) {
            ll_dialog_center.setVisibility(View.VISIBLE);
            tv_note.setText(mMessage);
        }
        //设置按钮
        if (cancelButton) {
            btn_negative.setVisibility(View.VISIBLE);
        } else {
            btn_negative.setVisibility(View.GONE);
        }
        if (yesButton) {
            btn_positive.setVisibility(View.VISIBLE);
        } else {
            btn_positive.setVisibility(View.GONE);
        }
        btn_negative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeDialog();
                if (negetiveListener != null) {
                    negetiveListener.onClick(v);
                }
            }
        });
        btn_positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeDialog();
                if (positiveListener != null) {
                    positiveListener.onClick(v);
                }
            }
        });
        if (mButtonResId != 0) {
            btn_negative.setBackgroundResource(mButtonResId);
            btn_positive.setBackgroundResource(mButtonResId);
        }
        //设置倒计时
        if (mCountTime > 0) {
            tv_time.setVisibility(View.VISIBLE);
            if (countTimer == null) {
                countTimer = new CountTimer(mCountTime, 1000);
            }
            countTimer.cancel();
            countTimer.start();
        } else {
            tv_time.setVisibility(View.GONE);
        }

    }

    //设置属性

    /**
     * 设置对话框宽高
     *
     * @param width  宽
     * @param height 高
     */
    public void setWidthAndHeight(int width, int height) {
        this.mWidth = width;
        this.mHeight = height;
    }

    public void setWidth(int width) {
        this.mWidth = width;
    }

    public void setHeight(int height) {
        this.mHeight = height;
    }

    /**
     * 设置位置属性
     *
     * @param gravity Gravity.CENTER
     *                Gravity.TOP
     *                Gravity.BOTTOM
     */
    public void setGravity(int gravity) {
        mGravity = gravity;
    }

    public void setPosition(boolean isRandPosition, int x, int y) {
        this.isRandPosition = isRandPosition;
        mPositionX = x;
        mPositionY = y;
    }

    public void setWindowAnimations(@StyleRes int windowAnimations) {
        mWindowAnimations = windowAnimations;
    }

    @Override
    public void setCanceledOnTouchOutside(boolean cancel) {
        super.setCanceledOnTouchOutside(cancel);
    }

    /**
     * 设置背景颜色
     *
     * @param backgroundColor color
     */
    public void setBackgroundColor(int backgroundColor) {
        this.mBackgroundColor = backgroundColor;
    }

    /**
     * 设置背景资源：图片、颜色、Drawable资源
     *
     * @param backgroundResId resId
     */
    public void setBackgroundResource(@DrawableRes int backgroundResId) {
        this.mBackgroundResId = backgroundResId;
    }

    public void setButtonBackground(@DrawableRes int backgroundResId) {
        this.mButtonResId = backgroundResId;
    }

    /**
     * 设置背景图
     *
     * @param drawable 图片
     */
    public void setBackground(Drawable drawable) {
        this.mBackgroundDrawable = drawable;
    }

    public void setTitle(String title) {
        this.mTitle = title;
    }

    public void setMessage(String message) {
        this.mMessage = message;
    }

    public void setCountTime(long countTime) {
        this.mCountTime = countTime;
    }

    /**
     * 设置取消按钮监听事件
     *
     * @param str      按钮名称
     * @param listener 监听事件
     */
    public void setNegativeButton(String str, View.OnClickListener listener) {
        btn_negative.setVisibility(View.VISIBLE);
        btn_negative.setText(str);
        this.cancelButton = true;
        this.negetiveListener = listener;
    }

    /**
     * 设置确认按钮监听事件
     *
     * @param str      按钮名称
     * @param listener 监听事件
     */
    public void setPositiveButton(String str, View.OnClickListener listener) {
        btn_positive.setVisibility(View.VISIBLE);
        btn_positive.setText(str);
        this.yesButton = true;
        this.positiveListener = listener;
    }


    private class CountTimer extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        private CountTimer(long millisInFuture, long countDownInterval) {

            super(millisInFuture + 50, countDownInterval);
            Log.i(TAG, "CountTimer: millisInFuture=" + millisInFuture);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            int count = (int) (millisUntilFinished / 1000);
            Log.i(TAG, "onTick: " + millisUntilFinished + ";count=" + count);
            //最后一秒不执行回调
            tv_time.setText("(" + (count) + "秒)");
        }

        @Override
        public void onFinish() {
            Log.i(TAG, "onFinish: ");
            tv_time.setText("(0秒)");
            if (CustomDialog.this.isShowing()) {
                CustomDialog.this.dismiss();
            }
            if (mListener != null) {
                mListener.onTimeout();
            }
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        Log.i(TAG, "onAttachedToWindow: ");
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        Log.i(TAG, "onDetachedFromWindow: ");
    }
}
